package nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.*;
import java.util.concurrent.atomic.AtomicInteger;

public class SelectorThreadGroup {

    private SelectorThread[] selectorThreads;

    private AtomicInteger total = new AtomicInteger(0);

    public SelectorThreadGroup(int num) {
        selectorThreads = new SelectorThread[num];
        for (int i = 0; i < num; i++) {
            selectorThreads[i] = new SelectorThread(this);
            new Thread(selectorThreads[i]).start();
        }
    }

    public void bind(int port) {
        try {
            ServerSocketChannel ssc = ServerSocketChannel.open();
            ssc.configureBlocking(false);
            ssc.bind(new InetSocketAddress(port));
            // 将ssc注册到一个selector上
            regToNextSelector(ssc);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public SelectorThread nextThread() {
        return selectorThreads[total.incrementAndGet() % selectorThreads.length];
    }

    public void regToNextSelector(Channel channel) {
        SelectorThread selectorThread = nextThread();
        selectorThread.getChannelQueue().add(channel);
        selectorThread.getSelector().wakeup();
//            try {
//                Selector selector = selectorThreads[total.incrementAndGet() % selectorThreads.length]
//                        .getSelector();
//                selector.wakeup();
//                server.register(
//                        selector,
//                        SelectionKey.OP_ACCEPT);
//            } catch (ClosedChannelException e) {
//                e.printStackTrace();
//            }
    }
}
